export default {
	namespaced: true,
	state() {
		return {
			// 初始的状态数据
			carts: uni.getStorageSync('carts') || []
		}
	},
	mutations: {
		addTocart(state, goods) {
			//如果点击的id是一样，就让他的数量加1.不用再一次推送在数组里面去
			const res = state.carts.find(item => item.goods_id === goods.goods_id)
			if (!res) {
				state.carts.push(goods)
			} else {
				res.goods_count += 1
			}
			this.commit('carts/setCartsStorge')
		},
		//添加到本地存储
		setCartsStorge(state) {
			uni.setStorageSync('carts', state.carts)
		},
		//添加切换事件，状态取反。重新储存新的数据
		toggleState(state, index) {
			state.carts[index].goods_state = !state.carts[index].goods_state
			this.commit('carts/setCartsStorge')
		},
		toggleAll(state, goods_state) {
			state.carts.forEach(item => item.goods_state = !goods_state)
		},
		decreaseCount(state, index) {
			if (state.carts[index].goods_count <= 1) return
			state.carts[index].goods_count--
		},
		increaseCount(state, index) {
			state.carts[index].goods_count++
		}
	},
	getters: {
		//合计购物车数量就是数组长度
		cartCount(state) {
			return state.carts.length
		},
		//全选反选状态绑定
		allChecked(state) {
			return state.carts.every(item => item.goods_state)
		},
		checkedCount(state) {
			return state.carts.reduce((acc, item) => {

				if (!item.goods_state) return acc

				return acc += item.goods_count

			}, 0)
		},
		sumCount(state) {
			return state.carts.reduce((acc, item) => {
				if (!item.goods_state) return acc
				return acc += item.goods_count * item.goods_price
			}, 0)
		}
	}
}
